import socket
import _thread
import time
import ctypes
import inspect

local_host = "127.0.0.1"
local_port = 7201
MAX_LISTEN = 50
port_list = []              # 所有可用端口
MAX_DATABLOCK = 4096
global_socket=""       # 全局socket

def LOG(log_str,log_lv=0):
    print(log_str)

def GetAvailablePort():
    for i in range(7202,7300):
        if i not in port_list:
            return i
    return 0

def GetServerSocket():
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.bind((local_host,local_port))
        sock.listen(MAX_LISTEN)
        return sock
    except Exception as e:
        LOG("创建服务端套接字失败 {}".format(str(e)))
        return 

def GetProxySocket(port):
    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.bind((local_host,port))
        sock.listen(MAX_LISTEN)
        return sock
    except Exception as e:
        LOG("[E] 创建代理服务套接字失败 {}".format(str(e)))
        return 

def GetPort(client_socket):
    LOG("[I] 获取列表")
    client_socket.send(str(','.join(str(i) for i in port_list)).encode('utf-8'))   # 发送完端口列表就退出   
    client_socket.close()

# 第二次就会发送失败 因为旧线程接受了，。，
def ForwardDataThread(src_socket,dst_socket,available_port):
    global port_list
    LOG("[I] 开始转发线程")
    while True:
        try:
            buf = src_socket.recv(MAX_DATABLOCK)
            if len(buf) == 0:   # 与代理请求断开连接了
                port_list.remove(available_port)    # 移除当前用的端口
                LOG("移除端口"+str(available_port))
                break  # 跳出循环
            global_socket.send(buf)
        except Exception as e:
            LOG("dst_socket 发送失败 {}".format(str(e)))
            break
    LOG("[I] 结束转发线程")

def Client_Thread(client_socket):
    global port_list
    global global_socket
    # client_socket.settimeout(3)
    buf = client_socket.recv(MAX_DATABLOCK)
    if buf == "GetList".encode('utf-8'): # 只是获取可用列表
        GetPort(client_socket)
        return 
    else:
        available_port = GetAvailablePort()
        if available_port == 0: # 没有可用端口了
            LOG("[E] 没有可用端口了")
            return 
        proxy_socket = GetProxySocket(available_port)
        if proxy_socket == None:    # 创建套接字失败
            LOG("[E] 创建套接字失败")
            return
        port_list.append(available_port)    # 记录已经使用的端口号
        while True:
            LOG("{} 端口等待连接".format(available_port))
            request_socket,addr = proxy_socket.accept() # 接受代理请求连接
            LOG("[I] 新的代理请求连接 {}".format(str(addr)))
            global_socket =  request_socket
            tid = _thread.start_new_thread(ForwardDataThread,(client_socket,request_socket,available_port))
            print(tid)
            while True:
                try:
                    buf = request_socket.recv(MAX_DATABLOCK)
                    print("接受新的数据{}".format(len(buf)))
                except Exception as e:
                    LOG("[I]与代理请求断开连接了{}".format(str(e)))
                    break
                if len(buf) == 0:   # 与代理请求断开连接了
                    break  # 跳出这个转发循环 等待下一个请求连接
                # LOG("发送！")
                client_socket.send(buf)
                # LOG("发送完毕")
    
def StartServer():
    server_socket = GetServerSocket()
    if server_socket == None:
        return 
    while True:
        client_socket,addr = server_socket.accept()
        LOG("接收到连接: {}".format(str(addr)))
        _thread.start_new_thread(Client_Thread,(client_socket,))

if __name__ == "__main__":
    StartServer()

# 设置端口立即复用
# 干掉 线程！！！！！！！！！！！！！